package com.biubiushop.socket.nio;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @author chenjia
 * @date 2019/7/19
 **/
public class SocketChannelClient {

    private static final Log log = LogFactory.get();

    public static void start(JSONObject jsonObject) throws IOException {
        //连接服务端
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));

        //接受服务器端响应
        //新开线程,负责接受服务端的响应数据
//        Selector selector = Selector.open();
//        socketChannel.configureBlocking(false);
//        socketChannel.register(selector, SelectionKey.OP_READ);
//        new Thread(new NioClientHandler(selector)).start();

        log.info("用户发起出纸指令");

        //向服务器发送指令
        String request = jsonObject.toJSONString();
        if (request != null && request.length() > 0) {
            socketChannel.write(Charset.forName("UTF-8").encode(request));
        }
        socketChannel.close();

    }


    public static void main(String[] args) {
        try {
            start(new JSONObject());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
